package vn.training.model.entity.ext;

import oracle.adf.share.ADFContext;
import oracle.adf.share.security.SecurityContext;

import oracle.jbo.AttributeList;
import oracle.jbo.JboException;
import oracle.jbo.server.EntityImpl;

import oracle.security.jps.ResourcePermission;

public class CustomEntityImpl extends EntityImpl {
    public CustomEntityImpl() {
        super();
    }
    
    @Override
    protected void create(AttributeList attributeList) {
        if (this.isInsertAllowed()) {
            super.create(attributeList);
        } else {
            throw new JboException("No permission to insert new data");
        }
    }
    
    private boolean isInsertAllowed() {
        String securityResourceType = (String)this.getEntityDef().getProperty("SecurityResourceType");
        String securityResourceName = (String)this.getEntityDef().getProperty("SecurityInsertResourceName");        
        String securityAction = (String)this.getEntityDef().getProperty("SecurityInsertAction");
        
        if (securityResourceName != null && securityResourceType != null && securityAction != null) {
            SecurityContext securityCtx = ADFContext.getCurrent().getSecurityContext();
            ResourcePermission resourcePermission = new ResourcePermission(securityResourceType, securityResourceName, securityAction);

            return securityCtx.hasPermission(resourcePermission);   
        }
        
        return true;
    }
}
